package com.boot.netty.server.handler;

import com.boot.netty.commons.dispatcher.NettyBeanDispatcher;
import com.boot.netty.commons.entity.BaseObjectInvoke;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@Sharable
public class ServerChannelHandlerAdapter extends ChannelHandlerAdapter {

    @Autowired
    private NettyBeanDispatcher nettyBeanDispatcher;

    private int lossConnectCount;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("{} -> [连接异常] {}通道异常，异常原因：{}", this.getClass().getName(),
                ctx.channel().id(), cause.getMessage());
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof String){
            if ("I-am-Alive".equals(msg))
                log.info("[心跳检测] 通道正常 当前活跃id{}",ctx.channel().id());
            return;
        }

        BaseObjectInvoke invoke = (BaseObjectInvoke) msg;
        this.nettyBeanDispatcher.dispatcher(ctx,invoke);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state() == IdleState.READER_IDLE) {
                lossConnectCount++;
                if (lossConnectCount>2){
                    log.info("{}释放不活跃链接=>{}",this.getClass(),ctx.channel().id());
                    ctx.channel().close();
                }
            }

        }else super.userEventTriggered(ctx, evt);

    }


}
